package org.yocastlong.mybatisplus.common.utils;

import org.yocastlong.mybatisplus.common.CommonConstants;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author 朱海龙
 * 2025/6/10 08:20
 */
public class HeaderContext {

    private static final ThreadLocal<Map<String, Object>> HEADER_THREAD_LOCAL = ThreadLocal.withInitial(() -> new HashMap<>(64));

    public static void setObject(String key, Object value) {
        if (Objects.isNull(key) || Objects.isNull(value)) {
            return;
        }
        final Map<String, Object> localMap = HEADER_THREAD_LOCAL.get();
        localMap.put(key, value);
    }

    public static <T> T getObject(String key) {
        if (Objects.isNull(key)) {
            return null;
        }
        final Map<String, Object> localMap = HEADER_THREAD_LOCAL.get();
        return (T) localMap.get(key);
    }


    public static void reset() {
        HEADER_THREAD_LOCAL.remove();
    }


    public static void setUserId(String value) {
        if (Objects.isNull(value)) {
            return;
        }
        setObject(CommonConstants.header.userId, value);
    }

    public static String getUserId(Objects value) {
        if (Objects.isNull(value)) {
            return null;
        }
        return HEADER_THREAD_LOCAL.get()
                                  .getOrDefault(CommonConstants.header.userId, "")
                                  .toString();
    }


    public static void setUsername(String value) {
        if (Objects.isNull(value)) {
            return;
        }
        setObject(CommonConstants.header.username, value);
    }

    public static String getUsername(Objects value) {
        if (Objects.isNull(value)) {
            return null;
        }
        return HEADER_THREAD_LOCAL.get()
                                  .getOrDefault(CommonConstants.header.username, "")
                                  .toString();
    }


    public static void setTenantId(String value) {
        if (Objects.isNull(value)) {
            return;
        }
        setObject(CommonConstants.header.tenantId, value);
    }

    public static String getTenantId(Objects value) {
        if (Objects.isNull(value)) {
            return null;
        }
        return HEADER_THREAD_LOCAL.get()
                                  .getOrDefault(CommonConstants.header.tenantId, "")
                                  .toString();
    }


}
